package com.edu.whty.controller;

import com.edu.whty.common.constants.CodeConstants;
import com.edu.whty.common.tools.kafka.CommonMessage;
import com.edu.whty.entity.base.ResponseEntity;
import com.edu.whty.service.SystemService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@RestController
@RequestMapping("/system")
public class SystemController {

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    SystemService systemService;

    @RequestMapping(value = "/init", method = RequestMethod.GET)
    public ResponseEntity init(@RequestParam("orgId") String orgId) {
        try {
            systemService.init(orgId);
        } catch (Exception e) {
            return ResponseEntity.getFailedResponse(CodeConstants.CONSTANT_RETURN_CODE_SYSTEM_ERROR, "初始化失败");
        }

        return ResponseEntity.getSuccessResponse();
    }

    @RequestMapping(value = "/upSync", method = RequestMethod.POST)
    public ResponseEntity upSync(HttpServletRequest request, HttpServletResponse response,
                                 @RequestBody CommonMessage commonMessage) {
        try {
            if (null == commonMessage) {
                return ResponseEntity.getFailedResponse(CodeConstants.CONSTANT_RETURN_CODE_SYSTEM_ERROR, "参数不能为空");
            } else {
                if (org.apache.commons.lang.StringUtils.isEmpty(commonMessage.getTable())) {
                    return ResponseEntity.getFailedResponse(CodeConstants.CONSTANT_RETURN_CODE_SYSTEM_ERROR, "table不能为空");
                }
                if (commonMessage.getData().size() == 0) {
                    return ResponseEntity.getFailedResponse(CodeConstants.CONSTANT_RETURN_CODE_SYSTEM_ERROR, "data不能为空");
                }
                systemService.upSync(commonMessage);
                return ResponseEntity.getSuccessResponse();
            }
        } catch (Exception e) {
            logger.error("上行同步异常：" + e.getMessage(), e);
            return ResponseEntity.getFailedResponse(CodeConstants.CONSTANT_RETURN_CODE_SYSTEM_ERROR, "上行同步异常");
        }
    }
}
